package com.zzt.lotterysystem.controller.handler;

import com.zzt.lotterysystem.common.errorcode.GlobalErrorCodeConstants;
import com.zzt.lotterysystem.common.exception.ControllerException;
import com.zzt.lotterysystem.common.exception.ServiceException;
import com.zzt.lotterysystem.common.pojo.CommonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * Created with IntelliJ IDEA.
 * Description
 * User: panda
 * Date: 2025-05-18
 * Time: 15:00
 */
@RestControllerAdvice // 可以捕获全局抛的异常
public class GlobalExceptionHandler {

    private final static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(ServiceException.class)
    public CommonResult<?> serviceException(ServiceException e){
        // 打印错误日志
        logger.error("ServiceException: ", e);
        // 构造错误结果
        return CommonResult.error(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(),
                e.getMsg());
    }

    @ExceptionHandler(ControllerException.class)
    public CommonResult<?> controllerException(ControllerException e){
        // 打印错误日志
        logger.error("ControllerException: ", e);
        // 构造错误结果
        return CommonResult.error(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(),
                e.getMsg());
    }

    @ExceptionHandler(Exception.class)
    public CommonResult<?> exception(Exception e){
        // 打印错误日志
        logger.error("服务异常: ", e);
        // 构造错误结果
        return CommonResult.error(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(),
                e.getMessage());
    }

}
